﻿using ERP.ERPSystem.WarehouseManagement.Dto;
using ERP.Team.ProductionSystem;
using ERP.Team.WarehouseManagement;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ERP.ERPSystem.DataAnalysis
{
    /// <summary>
    /// 数据分析-库存数据-xzc
    /// </summary>
    public class InventoryDataServices:ApplicationService, IInventoryDataServices
    {
        private readonly IRepository<Inventory> _inventoryRepository;
        private readonly IRepository<MaterialType> _materialtypeRepository;

        public InventoryDataServices(IRepository<Inventory> inventoryRepository, IRepository<MaterialType> materialtypeRepository)
        {
            _inventoryRepository = inventoryRepository;
            _materialtypeRepository = materialtypeRepository;
        }
        /// <summary>
        /// 库存数据查询
        /// </summary>
        /// <param name="inventorydatadto"></param>
        /// <returns></returns>
        public async Task<List<GetInventoryDataDto>> GetInventoryData(InventoryDataDto inventorydatadto)
        {
            var inventoryList = await _inventoryRepository.GetListAsync();
            var materialtypeList = await _materialtypeRepository.GetListAsync();
            var inventorymaterialtypeDto = from a in inventoryList
                                           join b in materialtypeList on a.ProductItem equals b.Id
                                           select new GetInventoryDataDto
                                           {
                                               Id = a.Id,
                                               ProductName = a.ProductName,
                                               Specs = a.Specs,
                                               GalleryNumber = a.GalleryNumber,
                                               Unit = a.Unit,
                                               Storage = a.Storage,
                                               Warehouse = a.Warehouse,
                                               ReservoirArea = a.ReservoirArea,
                                               BinLocation = a.BinLocation,
                                               SupplierNumber = a.SupplierNumber,
                                               SupplierName = a.SupplierName,
                                               SupplierAbbreviation = a.SupplierAbbreviation,
                                               ProduceTickets = a.ProduceTickets,
                                               StorageDate = a.StorageDate,
                                               Storagevalidity = a.Storagevalidity,
                                               MaterialTypeName = b.MaterialTypeName,
                                               Index = b.Index,
                                               ParentId = b.ParentId,
                                               State = b.State,
                                               CreateTime = b.CreateTime
                                           };
            inventorymaterialtypeDto = inventorymaterialtypeDto.WhereIf(!string.IsNullOrEmpty(inventorydatadto.ProductName), m => m.ProductName == inventorydatadto.ProductName);
            inventorymaterialtypeDto = inventorymaterialtypeDto.WhereIf(!string.IsNullOrEmpty(inventorydatadto.SupplierName), m => m.SupplierName.Contains(inventorydatadto.SupplierName));
            inventorymaterialtypeDto = inventorymaterialtypeDto.WhereIf(!string.IsNullOrEmpty(inventorydatadto.Warehouse), m => m.Warehouse == inventorydatadto.Warehouse);
            inventorymaterialtypeDto = inventorymaterialtypeDto.WhereIf(!string.IsNullOrEmpty(inventorydatadto.Storagevalidity.ToString()), m => m.Storagevalidity == inventorydatadto.Storagevalidity);
            return inventorymaterialtypeDto.ToList();
        }
        /// <summary>
        /// 查询物料产品分类出局
        /// </summary>
        /// <returns></returns>
        public async Task<List<Inventory>> GetMaterialType()
        {
            var materialtypeList = await _inventoryRepository.GetListAsync();
            return materialtypeList;
        }

        public async Task<List<InventoryChartDto>> GetInventoryChartDataAsync()
        {
            var query = await _inventoryRepository.GetQueryableAsync();
            
            var chartData = await AsyncExecuter.ToListAsync(
                query.Select(x => new InventoryChartDto
                {
                    ProductName = x.ProductName,
                    GalleryNumber = x.GalleryNumber
                })
            );

            return chartData;
        }

        public async Task<List<InventoryPieChartDto>> GetInventoryPieChartDataAsync()
        {
            var query = await _inventoryRepository.GetQueryableAsync();
            
            // 获取所有数据并计算总数
            var inventoryData = await AsyncExecuter.ToListAsync(query);
            var totalGalleryNumber = inventoryData.Sum(x => x.GalleryNumber);

            // 按ProductName分组并计算占比
            var result = inventoryData
                .GroupBy(x => x.ProductName)
                .Select(g => new InventoryPieChartDto
                {
                    ProductName = g.Key,
                    GalleryNumber = g.Sum(x => x.GalleryNumber),
                    Percentage = totalGalleryNumber > 0 
                        ? decimal.Round((decimal)g.Sum(x => x.GalleryNumber) / totalGalleryNumber * 100, 2)
                        : 0
                })
                .OrderByDescending(x => x.GalleryNumber)
                .ToList();

            return result;
        }

        public async Task<InventoryStatisticsDto> GetInventoryStatisticsAsync()
        {
            var query = await _inventoryRepository.GetQueryableAsync();
            
            var statistics = new InventoryStatisticsDto
            {
                // 计算GalleryNumber总和
                TotalGalleryNumber = query.Sum(x => x.GalleryNumber),
                
                // 统计去重后的ProductName数量
                ProductTypeCount = query.Select(x => x.ProductName).Distinct().Count(),
                
                // 统计去重后的Warehouse数量
                WarehouseCount = query.Select(x => x.Warehouse).Distinct().Count()
            };

            return statistics;
        }
    }
}
